package com.happy.zebra.admin.ui.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.happy.zebra.admin.ui.entity.SysDict;
import com.happy.zebra.admin.ui.mapper.SysDictMapper;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import javax.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@AllArgsConstructor
@RequestMapping("/dict")
@Api(value = "dict", description = "字典管理模块")
public class DictController {

	private final SysDictMapper sysDictMapper;

	@GetMapping("/page")
	public R<IPage> getDictPage(Page page, SysDict sysDict) {

		if (StringUtils.isEmpty(sysDict.getType())) {
			sysDict.setType(null);
		}

		return new R<>(sysDictMapper.getDictPage(page, sysDict));
	}

	@PostMapping("/saveJson")
	public R<Boolean> saveJson(@RequestBody SysDict sysDict) {
		return new R<>(sysDictMapper.saveJson(sysDict) == 1);
	}

	/**
	 * 添加字典
	 *
	 * @param sysDict 字典信息
	 * @return success、false
	 */
	@SysLog("添加字典")
	@PostMapping
	@CacheEvict(value = "dict_details", key = "#sysDict.type")
	public R save(@RequestBody SysDict sysDict) {

		//判断字典是否是json格式
		if ("1".equals(sysDict.getIsJson())) {
			sysDict.setDescription("{\"key\":\"value\"}");
		}

		return new R<>(sysDictMapper.saveDict(sysDict) == 1);
	}

}
